import axios from 'axios'

const baseURL = 'http://localhost:8080'

const request = axios.create({
    baseURL,
    timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 添加CORS相关headers
        config.headers['Access-Control-Allow-Origin'] = '*'
        config.headers['Content-Type'] = 'application/json'
        config.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
        config.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        console.log('API响应：', response) // 调试日志
        return response.data
    },
    error => {
        console.error('API错误：', error.response)
        return Promise.reject(error)
    }
)

// 获取所有班级
export const getAllClasses = async () => {
    try {
        const response = await request.get('/class')
        return response.data
    } catch (error) {
        console.error('获取班级列表出错:', error)
        throw error
    }
}

// 获取所有学生
export const getAllStudents = async () => {
    try {
        const response = await request.get('/students')
        return response.data
    } catch (error) {
        console.error('获取学生列表出错:', error)
        throw error
    }
}

// 获取所有学期
export const getAllSemesters = async () => {
    try {
        const response = await request.get('/semesters')
        return response.data
    } catch (error) {
        console.error('获取学期列表出错:', error)
        throw error
    }
}

// 根据总分排序获取学生
export const getStudentsSortedByTotalScore = async (order = 'desc') => {
    try {
        const response = await request.get('/students', {
            params: { sort: 'totalScore', order }
        })
        return response.data
    } catch (error) {
        console.error('按总分排序获取学生出错:', error)
        throw error
    }
}

// 添加学生
export const addStudent = async (studentData) => {
    try {
        const response = await request.post('/students', studentData)
        return response.data
    } catch (error) {
        console.error('添加学生出错:', error)
        throw error
    }
}

// 更新学生信息
export const updateStudent = async (studentId, studentData) => {
    try {
        const response = await request.put(`/students/${studentId}`, studentData)
        return response.data
    } catch (error) {
        console.error('更新学生信息出错:', error)
        throw error
    }
}

// 删除学生
export const deleteStudent = async (studentId) => {
    try {
        const response = await request.delete(`/students/${studentId}`)
        return response.data
    } catch (error) {
        console.error('删除学生出错:', error)
        throw error
    }
}

// API接口集合
const api = {
    punishment: {
        getAll: () => request.get('/punishment'),
        getByStudentId: (studentId) => request.get(`/punishment?studentId=${studentId}`),
        add: (data) => request.post('/punishment', data),
        update: (data) => request.put('/punishment', data),
        delete: (id) => request.delete(`/punishment/${id}`),
        review: (id) => request.put(`/punishment/review/${id}`),
        deleteById: (id) => request.delete(`/punishment/${id}`)
    },
    reward: {
        getAll: () => request.get('/reward'),
        getByStudentId: (studentId) => request.get(`/reward?studentId=${studentId}`),
        add: (data) => request.post('/reward', data),
        update: (data) => request.put('/reward', data),
        delete: (id) => request.delete(`/reward/${id}`),
        review: (id) => request.put(`/reward/review/${id}`)
    },
    class: {
        getAll: () => request.get('/class'),
        getById: (id) => request.get(`/class/${id}`),
        add: (data) => request.post('/class', data),
        update: (data) => request.put(`/class/${data.id}`, data),
        delete: (id) => request.delete(`/class/${id}`),
        search: (query) => request.get(`/class/search?query=${query}`),
        filterByGrade: (grade) => request.get(`/class/filter?grade=${grade}`)
    },
    student: {
        getAll: () => request.get('/students'),
        add: (data) => request.post('/students', data),
        update: (data) => request.put('/students', data),
        delete: (id) => request.delete(`/students/${id}`)
    },
    department: {
        getAll: () => request.get('/department'),
        add: (data) => request.post('/department', data),
        update: (data) => request.put('/department', data),
        delete: (code) => request.delete(`/department/${code}`)
    },
    teacher: {
        getAll: () => request.get('/teacher'),
        // ... other methods ...
    }
}

export default api
